package com.kotlin.lib.coroutines

import kotlinx.coroutines.*

fun main() = runBlocking<Unit> {

    val job = launch {
        try {
            repeat(1000) {
                println("i'm running $it")
                delay(500)
            }
        } finally {//不可取消的协程block
            withContext(NonCancellable) {
                println("finally run")
                delay(1000)
                println("i'm after delay.")
            }
        }
    }

    delay(2000)
    println("i'm tired of waiting")
    job.cancelAndJoin()
    println("over.")
    var result = withTimeoutOrNull(2000) {
        var index = 0
        while (index < 5000) {
            println("timeOut:$index")
            delay(200)
            index++
        }
        "DONE"
    }
    println("result:$result")
    println("****************************************")
    result = withTimeout(2000) {
        var index = 0
        while (index < 5000) {
            println("timeOut:$index")
            delay(200)
            index++
        }
        "done"
    }

    println("result:$result")
}